//
//  SHComposeViewController.swift
//  SHWeibo3
//
//  Created by teacher on 16/7/26.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class SHComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        // 01 添加控件
        view.addSubview(composeTextView)
        composeTextView.addSubview(composePictureView)
        view.addSubview(composeToolbarView)
        // 02 添加约束
        // 01
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        // 02
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
        }
        // 03
        composeToolbarView.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(44)
            make.leading.trailing.bottom.equalTo(view)
        }
        
        // 监听按钮点击
        composeToolbarView.closure = {[weak self](type: SHComposeToolbarViewType)->() in
            
            switch type{
            case .Picture:
                print("图片")
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .Add:
                print("+")

            }
            
        }
        
        // 监听配图中加号cell点击 弹出相册
        composePictureView.closure = {[weak self] in
            self?.selectImage()
        }
        // 监听键盘将要改变frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 表情键盘删除按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButton", name: WBEmoticonDeleteButtonNoti, object: nil)
        // 表情键盘按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtons:", name: WBEmoticonButtonsNoti, object: nil)
        
    }
    // MARK: - 监听方法
    //表情键盘按钮通知点击方法
    func emoticonButtons(noti: NSNotification){
        // 判断他是否为nil 而且是否可以转成Emoticon 模型
        guard let emoticon = noti.object as? SHEmoticon else{
            return
        }
        
        // 判断是否是emoji表情
        if emoticon.isEmoji {
            // 十六进制字符串转格式
            let codeStr = (emoticon.code ?? "" as NSString).emoji()
            composeTextView.insertText(codeStr)
        }else{
            // 代表是图片表情
            // 获取当前composeTextView 的富文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
//            // 文本附件
//            let att = SHTextAttachment()
//            // 赋值
//            att.emoticon = emoticon
//            // 设置image
//            att.image = UIImage.getEmoticonImage(emoticon.path)
//            // 计算行高
//            let lineHeight = composeTextView.font!.lineHeight
//            // 记住一定要设置bounds
//            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
//            // 不可变的富文本
//            let attr = NSAttributedString(attachment: att)
            let lineHeight = composeTextView.font!.lineHeight
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)
            // 获取当期选中的光标
            let selectedRange = composeTextView.selectedRange
            // 拼接 - 失败
            //allAttr.appendAttributedString(attr)
            // 插入不可变富文本 - 失败
           // allAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            // 设置富文本属性
            allAttr.addAttributes([NSFontAttributeName: composeTextView.font!], range: NSRange(location: 0, length: allAttr.length))
            // 赋值
            composeTextView.attributedText = allAttr
            // 重新设置composeTextView 选中光标
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            // 发送一个通知 告知textView 隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            // 主动条用代理方法 改变右侧按钮状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
    
    // 表情键盘中的删除按钮点击方法
    func emoticonDeleteButton(){
        composeTextView.deleteBackward()
    }

    // 监听键盘改变
    func keyboardWillChangeFrame(noti: NSNotification){
        // 判断是否为nil
        guard let userInfo = noti.userInfo else{
            return
        }
        // 获取时间
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        // 通过key 获取value frame
        let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        // 获取rect
        let rect = value.CGRectValue()
        
        self.composeToolbarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        // 设置动画
        UIView.animateWithDuration(Double(duration)) { () -> Void in
            self.composeToolbarView.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelAciton")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, target: self, action: "sendAciton")
        //
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    // 取消
    func cancelAciton(){
        // 取消第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 发布
    func sendAciton(){
        // 图片表情 -> 图片描述     "表1234"    "[马到成功]1234"
        // 01 遍历的结果
        // 02 遍历的范围
        // 03 遍历是否停止
        // 定义一个可变的字符串
        var allText = ""
        // 遍历composeTextView.attributedText
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            // 代表输入的是文本附件
            if let att = result["NSAttachment"] as? SHTextAttachment {
                allText += (att.emoticon?.chs ?? "")
            }else{
                // 文字
                // 字符串截取
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
            }
        }
        // 发送微博
        composePictureView.imageList.count > 0 ? upload(allText):update(allText)
        
    }
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        // 用户名字
        let name = SHUserAccountViewModel.sharedTools.userAccount?.screen_name ?? ""
        let str = "发微博\n\(name)"
        // 获取range
        let range = (str as NSString).rangeOfString(name)
        // 创建一个可变的富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.attributedText = attr
        lab.sizeToFit()
        return lab
    }()
    // 自定义textView
    //  在ios7 以后 如果系统检测到有导航栏 直接帮textView 的输入文字向下移动
    private lazy var composeTextView: SHComposeTextView = {
        let view = SHComposeTextView()
        view.delegate = self
        view.font = UIFont.systemFontOfSize(16)
        view.placeholder = "上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博"
        view.alwaysBounceVertical = true
        return view
    }()
    // 配图
    private lazy var composePictureView: SHComposePictureView = SHComposePictureView()
    // 底部视图
    private lazy var composeToolbarView: SHComposeToolbarView = SHComposeToolbarView()
    // 自定义表情键盘
    private lazy var emoticonKeyboardView: SHEmoticonKeyboardView = SHEmoticonKeyboardView()
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: -底部视图按钮点击回调
extension SHComposeViewController {
    // 打开相册
    func selectImage(){
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
        
    }
    
    // 切换键盘
    func switchKeyboard(){
        // 如果inputView 为nil  代表当前为系统键盘
        if composeTextView.inputView == nil {
            composeTextView.inputView = emoticonKeyboardView
            composeToolbarView.isEmoticon = true
        }else {
            // 反之代表是自定义表情键盘
            composeTextView.inputView = nil
            composeToolbarView.isEmoticon = false
        }
        // 刷新reloadInputViews
        composeTextView.reloadInputViews()
        // 设置第一响应者
        composeTextView.becomeFirstResponder()
    }
}
// MARK: -UIImagePickerControllerDelegate
extension SHComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        composePictureView.addImages(image.getImageScale(600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK: - UITextViewDelegate
extension SHComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 取消第一响应
        self.composeTextView.resignFirstResponder()
    }
}
// MARK: - 发送微博
extension SHComposeViewController {
    // 发送文字微博
    func update(status: String){
        SHNetworkTools.sharedTools.composeUpdate(status, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发送失败")
        }

    }
    
    // 发送图片微博
    func upload(status: String){
       SHNetworkTools.sharedTools.composeUpload(status, imageList: composePictureView.imageList, success: { (response) -> () in
        SVProgressHUD.showSuccessWithStatus("发布成功")
        }) { (error) -> () in
            SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
    }
}














